from app import ma
from .models import Recipe, RecipeStep, RecipeIngredient, RecipeTag

# 1. 食谱步骤 Schema（无跨模块嵌套，直接定义）
class RecipeStepSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = RecipeStep
        load_instance = True
        # 让Marshmallow自动发现所有字段，避免版本兼容性问题

recipe_step_schema = RecipeStepSchema()
recipe_steps_schema = RecipeStepSchema(many=True)

# 2. 食谱-食材关联 Schema（嵌套 IngredientSimpleSchema，明确指定字段）
class RecipeIngredientSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = RecipeIngredient
        load_instance = True
        fields = ('id', 'quantity', 'unit', 'ingredient')  # 明确指定需要序列化的字段
    
    # 字符串引用食材 Schema，明确指定需要的字段
    ingredient = ma.Nested('app.ingredients.schemas.IngredientSimpleSchema', many=False, exclude=())

recipe_ingredient_schema = RecipeIngredientSchema()
recipe_ingredients_schema = RecipeIngredientSchema(many=True)

# 3. 食谱-标签关联 Schema（嵌套 TagSchema，用字符串引用）
class RecipeTagSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = RecipeTag
        load_instance = True
        # 让Marshmallow自动发现所有字段，避免版本兼容性问题
    
    # 【修复】使用仅包含id和name的简化标签Schema，避免循环引用问题
    tag = ma.Nested('app.tags.schemas.TagSchema', many=False, only=('id', 'name'))

recipe_tag_schema = RecipeTagSchema()
recipe_tags_schema = RecipeTagSchema(many=True)

# 4. 简化版食谱 Schema（供 NutritionSchema 嵌套，避免循环）
class RecipeSimpleSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Recipe
        load_instance = True
        fields = ('id', 'title', 'description', 'cover_image', 'category', 'difficulty', 'cook_time', 'servings', 'tags', 'ingredients')
    
    # 字符串引用分类 Schema，避免跨模块循环
    category = ma.Nested('app.categories.schemas.CategorySchema', many=False)
    # 添加标签字段，使食谱列表也能返回标签信息
    tags = ma.Nested(RecipeTagSchema, many=True)
    # 使用attribute参数确保正确引用recipe_ingredients关系，同时保持原有的ingredients字段名称
    ingredients = ma.Nested(RecipeIngredientSchema, many=True, attribute='recipe_ingredients')

recipe_simple_schema = RecipeSimpleSchema()
recipes_simple_schema = RecipeSimpleSchema(many=True)

# 5. 完整食谱 Schema（多嵌套统一用字符串引用）
class RecipeSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Recipe
        load_instance = True
        # 让Marshmallow自动发现所有字段，避免版本兼容性问题
    
    # 【关键修复】所有跨模块嵌套均用字符串引用
    category = ma.Nested('app.categories.schemas.CategorySchema', many=False)
    steps = ma.Nested(RecipeStepSchema, many=True)
    # 使用attribute参数确保正确引用recipe_ingredients关系
    ingredients = ma.Nested(RecipeIngredientSchema, many=True, attribute='recipe_ingredients')
    # 【优化】直接使用TagSchema并限制字段，确保返回标签名称
    tags = ma.Nested('app.tags.schemas.TagSchema', many=True, only=('id', 'name'))
    comments = ma.Nested('app.comments.schemas.CommentSchema', many=True)

# 实例化食谱序列化器
recipe_schema = RecipeSchema()
recipes_schema = RecipeSchema(many=True)